package tech.daoxuan.web.controller;

import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import tech.daoxuan.web.entity.FileInfos;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Date;

@RestController
@RequestMapping("/file")
public class FileController {

    Logger logger = LoggerFactory.getLogger(FileController.class);

    String folder = "D:\\Project\\daoxuan-security\\daoxuan-security-demo\\src\\main\\java\\tech\\daoxuan\\web\\controller";

    /**
     *
     * @param file  这个形参 和 上传时的名字一样
     * @return
     * @throws IOException
     */
    @PostMapping
    public FileInfos upload(MultipartFile file) throws IOException {
        String name = file.getName();
        logger.info("上传参数的名字" + name);
        logger.info("上传文件的名字" + file.getOriginalFilename());
        logger.info("上传文件的尺寸" + file.getSize());

        File file1 = new File(folder, new Date().getTime() + ".txt");
        file.transferTo(file1);//写到本地文件，生产时可以 用inputstream  发送到 文件服务器
        return new FileInfos(file1.getAbsolutePath());
    }


    @GetMapping("/{id}")
    public void downLoad(@PathVariable  String id, HttpServletRequest request, HttpServletResponse response){
        try {
            FileInputStream fileInputStream = new FileInputStream(new File(folder, id + ".txt"));
            OutputStream outputStream = response.getOutputStream();

            response.setContentType("application/x-download");
            response.addHeader("Content-Disposition","attachment;filename=test.txt");
            IOUtils.copy(fileInputStream, outputStream);
            outputStream.flush();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
